package model

import (
	"blog/global"
	"blog/model/response"
	"encoding/base64"
	"golang.org/x/crypto/scrypt"
	"gorm.io/gorm"
	"log"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null " json:"username" validate:"required,min=4,max=12" label:"用户名"`
	Password string `gorm:"type:varchar(500);not null" json:"password" validate:"required,min=6,max=120" label:"密码"`
	Role     int    `gorm:"type:int;DEFAULT:2" json:"role" validate:"required,gte=2" label:"角色码"`
}

//查询用户是否存在
func CheckUsername(name string) int {
	var user User
	global.DB.Select("id").Where("username = ?", name).First(&user)
	if user.ID > 0 {
		return response.ERROR_USERNAME_USED

	}
	return response.SUCCESS
}

//添加用户
func CreateUser(user *User) int {
	//加密存入数据库
	user.Password = ScryptPassword(user.Password)
	err := global.DB.Create(&user).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS

}

//密码加密
func ScryptPassword(password string) string {
	const keyLen = 10
	salt := make([]byte, 8)
	salt = []byte{12, 56, 8, 30, 79, 12, 14, 24}
	hsahPassword, err := scrypt.Key([]byte(password), salt, 4096, 8, 1, keyLen)
	if err != nil {
		log.Fatal(nil)
	}
	return base64.StdEncoding.EncodeToString(hsahPassword)
}

//查询用户列表
func GetUsers(pageSize int, pageNum int) []User {
	var users []User
	err := global.DB.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil
	}
	return users
}

//编辑用户
func EditUser(id int, user *User) int {
	var maps = make(map[string]interface{})
	maps["username"] = user.Username
	maps["role"] = user.Role
	err := global.DB.Model(&User{}).Where("id=?", id).Updates(maps).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS
}

//删除用户
func DeleteUser(id int) int {
	var user User
	err := global.DB.Where("id=?", id).Delete(&user).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS
}

// CheckLogin 后台登录验证
func CheckLogin(username string, password string) (User, int) {
	var user User

	global.DB.Where("username = ?", username).First(&user)

	if user.ID == 0 {
		return user, response.ERROR_USER_NOT_EXIST
	}
	if ScryptPassword(password) != user.Password {
		return user, response.ERROR_PASSWORD_WRONG
	}
	if user.Role != 1 {
		return user, response.ERROR_USER_NO_RIGHT
	}
	return user, response.SUCCESS
}
